package com.example.contestsystem.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.ui.Model;
import com.example.contestsystem.Entity.*;
import com.example.contestsystem.R.R;
import com.example.contestsystem.Service.ContestService;
import com.example.contestsystem.Service.FileService;
import com.example.contestsystem.Service.SignUpContestService;
import com.example.contestsystem.Service.TeamService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.Resource;
@Controller
@RequestMapping("/contestindex")
public class ContestIndexController {

    final ContestService contestService;
    final SignUpContestService signUpContestService;
    final FileService fileService;
    final TeamService teamService;
    private static final String UPLOAD_DIR = "D:\\Reserved\\";

    public ContestIndexController(ContestService contestService, SignUpContestService signUpContestService,
                                  FileService fileService, TeamService teamService) {
        this.contestService = contestService;
        this.signUpContestService = signUpContestService;
        this.fileService = fileService;
        this.teamService = teamService;
    }


    /**
     * 此方法实现学生报名比赛
     * 修改表sign_up_contest
     *
     * @return 已通过测试
     */
    @GetMapping("/signup")
    public String participate(@Param("contestId") String contestId, @Param("contestName") String contestName,Model model) {
        Contest contest = this.contestService.findByContestId(contestId);
        model.addAttribute("contest", contest);
       return "stu/signup";
    }
    @PostMapping("/signup")
    public String processSignupForm(@RequestParam("contestId") String contestId, HttpServletRequest httpServletRequest, Model model) {
        // 处理报名信息，例如保存到数据库
        // 这里可以调用服务层来处理报名逻辑
        // 假设有一个名为applicantService的服务类来处理报名逻辑
        Contest contest = this.contestService.findByContestId(contestId);
        Student loginStu = (Student) httpServletRequest.getSession().getAttribute("loginStu");
        if (loginStu != null) {
            SignUpContest signUpContest = new SignUpContest();
            signUpContest.setContestId(contest.getContestId());
            signUpContest.setStuAccount(loginStu.getStuAccount());
            if (this.signUpContestService.participate(signUpContest) != null) {
                //选择创建队伍还是加入队伍 如果里面的是创建队伍
                model.addAttribute("panduan", 1);
                return "redirect:/contestindex/stu/index";
            }
            }

        model.addAttribute("panduan",0);
        return "redirect:/contestindex/stu/list";

    }



    /**
     * 此方法实现查看竞赛详情（竞赛信息，竞赛的文件）
     * 通过点击即可查看
     */
    @GetMapping("stu/detail/{contestId}")
    public String detailindex(@PathVariable("contestId") String contestId, HttpServletRequest httpServletRequest, Model model) {
        Contest contest = this.contestService.findByContestId(contestId);
        System.out.print(contestId);
        List<FileEntity> fileEntities = this.contestService.findFilesByContestId(contestId);
        // 如果有学生登录了，且登录学生参加了该比赛，显示该小组信息和成员列表
        Student loginStu = (Student) httpServletRequest.getSession().getAttribute("loginStu");
        if (loginStu != null) {
            Team team = this.teamService.findByStuAccountAndContestId(loginStu.getStuAccount(), contestId);
            if (team != null) {
                List<Student> students = this.teamService.findMember(team.getTeamId());
                model.addAttribute("team", team);
                model.addAttribute("member", students);
            }

        }
        model.addAttribute("contest", contest);
        model.addAttribute("files", fileEntities);
        return "stu/jingsaixinxi/detail";

    }
    @GetMapping("teacher/detail/{contestId}")
    public String detailtindex(@PathVariable("contestId") String contestId, HttpServletRequest httpServletRequest, Model model) {
        Contest contest = this.contestService.findByContestId(contestId);
        System.out.print(contestId);
        List<FileEntity> fileEntities = this.contestService.findFilesByContestId(contestId);
        // 如果有老师登录了，且该比赛由登录老师发布，则显示小组列表
        Teacher loginTeacher = (Teacher) httpServletRequest.getSession().getAttribute("loginTeacher");
        if (loginTeacher != null && this.contestService.isPublisher(contestId, loginTeacher.getTeacherAccount())) {
            List<Team> teams = this.teamService.findByContestId(contestId);
            if (teams != null){
                model.addAttribute("teams", teams);
            }
        }
        model.addAttribute("contest", contest);
        model.addAttribute("files", fileEntities);
        return "teacher/jingsaixinxi/detail";
    }
    /**
     * 实现全部数据查询在首页显示
     */
    @GetMapping({"/stu/index", "/stu/index.html"})
    public String index(Model model) {
        List<Contest> contestList = contestService.findAllContest(); // 获取数据库中的所有数据
        model.addAttribute("contestList", contestList); // 将数据传递给首页的HTML页面
        //  List<FileEntity> fileList = fileService.findAllFileEntity(); // 获取数据库中的所有数据
        //model.addAttribute("fileList", fileList); // 将数据传递给首页的HTML页面
        return "stu/index"; // 返回首页的HTML页面 一定要返回不然找不到
    }
    /**
     * 实现全部数据查询在首页显示
     */
    @GetMapping({"/teacher/index", "/teacher/index.html"})
    public String teacherindex(Model model) {
        List<Contest> contestList = contestService.findAllContest(); // 获取数据库中的所有数据
        model.addAttribute("contestList", contestList); // 将数据传递给首页的HTML页面
        //  List<FileEntity> fileList = fileService.findAllFileEntity(); // 获取数据库中的所有数据
        //model.addAttribute("fileList", fileList); // 将数据传递给首页的HTML页面
        return "teacher/index"; // 返回首页的HTML页面 一定要返回不然找不到
    }
/**
 * 该方法实现查看所有竞赛信息学生
 */
@GetMapping("/stu/list")
public String list(Model model) {

    List<Contest> contestList = contestService.findAllContest(); // 获取数据库中的所有数据
    model.addAttribute("contestList", contestList); // 将数据传递给首页的HTML页面
    //  List<FileEntity> fileList = fileService.findAllFileEntity(); // 获取数据库中的所有数据
    //model.addAttribute("fileList", fileList); // 将数据传递给首页的HTML页面
    return "stu/jingsaixinxi/list"; // 返回首页的HTML页面 一定要返回不然找不到
}
    /**
     * 该方法实现查看所有竞赛信息老师
     */
    @GetMapping("/teacher/list")
    public String listteacher(Model model) {

        List<Contest> contestList = contestService.findAllContest(); // 获取数据库中的所有数据
        model.addAttribute("contestList", contestList); // 将数据传递给首页的HTML页面
        //  List<FileEntity> fileList = fileService.findAllFileEntity(); // 获取数据库中的所有数据
        //model.addAttribute("fileList", fileList); // 将数据传递给首页的HTML页面
        return "teacher/jingsaixinxi/list"; // 返回首页的HTML页面 一定要返回不然找不到
    }


    /**
     * 此方法实现下载文件
     *
     * @param fileName 文件名
     */
    @GetMapping("/download/{contestId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String contestId, @RequestParam String fileName) throws IOException {

        String filePath = UPLOAD_DIR + contestId + File.separator + fileName;
        Path path = Paths.get(filePath);
        if (Files.exists(path)) {
            // 文件存在，执行文件读取操作
            System.out.print("有文件");
            // ... 读取文件的二进制数据并返回
            // 包装了文件的二进制数据，并设置了Content-Disposition响应头，告诉浏览器将文件作为附件下载
            Resource resource = new InputStreamResource(Files.newInputStream(path));
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            // 返回响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);

        } else {
            // 文件不存在，处理文件不存在的情况
            // ... 可以抛出异常或者进行其他处理
            System.out.print("失败，没有文件");
        }
        //File file = new File(filePath);
        //将文件作为资源加载

        //设置响应头
        /** HttpHeaders headers = new HttpHeaders();
         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
         headers.setContentDispositionFormData("attachment", fileName);
         return new ResponseEntity<>(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK);
         **/
        return ResponseEntity.notFound().build();
    }
    /**
     * 实现根据竞赛名称跳转到竞赛详情页
     */
    @GetMapping("/stu/search")
    public String searchContest(@RequestParam("contestName") String contestName, Model model) {
        // 调用后端服务来根据竞赛名称查找竞赛
        Contest contest = contestService.findContestByName(contestName);
        // 将查找到的竞赛数据传递给前端页面
        model.addAttribute("contest", contest);
        // 返回显示查找结果的页面
        return "stu/jingsaixinxi/detail";
    }
    @GetMapping("/teacher/search")
    public String searchContestteacher(@RequestParam("contestName") String contestName, Model model) {
        // 调用后端服务来根据竞赛名称查找竞赛
        Contest contest = contestService.findContestByName(contestName);
        // 将查找到的竞赛数据传递给前端页面
        model.addAttribute("contest", contest);
        // 返回显示查找结果的页面
        return "teacher/jingsaixinxi/detail";
    }
}

